/**
 * 音频播放类
 */
import audio from '@system.audio'
import ajax from '../services/ajax';
import config from '../config';
import prompt from '@system.prompt';

class Audio {
    /** 播放完成回调函数集合 */
    onendedCallbackBack = []
    /** 开始播放回调函数集合 */
    onplayCallbackBack = []
    url = ""
    constructor() {
        console.log("Audio 初始成功，添加ended事件")
        // 音频是否在通知栏中显示音频播放状态，默认 true
        audio.notificationVisible = false;
        audio.onended = () => {
            console.log("播放完成");
            this.onendedCallbackBack.forEach(callback => callback());
        }
        audio.onplay = () => {
            console.log("开始播放");
            this.onplayCallbackBack.forEach(callback => callback());
        }
        audio.onerror = (err) => {
            console.log("播放失败:", err);
            prompt.showToast({ message: "播放失败" });
        }
    }
    async playSystem(type) {
        audio.src = `${config.API_HOST}/system-sound/${type}.mp3`;
        console.log("播放:", audio.src);
        audio.play();
    }
    async play(text) {
        console.log("play text=", text, ', this.url=', this.url);
        if (!text && this.url) {
            audio.src = this.url;
            audio.play();
            return;
        } else if(!text && !this.url) {
            console.log("没有可播放的音频地址");
            return;
        }
        const options = {
            'method': 'POST',
            'url': `/tts`,
            data: {
                text
            }
        }
        return ajax.fetch(options).then(mp3Url => {
            const src = `${config.API_HOST}/${mp3Url}`;
            this.url = src;
            audio.src = src;
            console.log("播放:", src);
            audio.play();
            return src;
        });
    }
    /** 添加播放完成回调 */
    onended(callback) {
        this.onendedCallbackBack.push(callback);
    }
    onplay(callback) {
        this.onplayCallbackBack.push(callback);
    }
    stop() {
        audio.stop();
    }
    distory() {
        this.onendedCallbackBack = [];
        this.onplayCallbackBack = [];
        this.stop();
    }
}

export default Audio;